
import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { CheckCircle, ExternalLink, Target } from "lucide-react";
import { RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar, ResponsiveContainer } from "recharts";
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";

interface Statement {
  id: string;
  text: string;
  category: 'creativity' | 'communication' | 'leadership' | 'planning' | 'collaboration';
}

const statements: Statement[] = [
  { id: "1", text: "I bring visual clarity into complex teaching content", category: "creativity" },
  { id: "2", text: "I enjoy guiding peer teachers or mentoring students", category: "leadership" },
  { id: "3", text: "I initiate interdisciplinary collaborations", category: "collaboration" },
  { id: "4", text: "I frequently gather and use student feedback", category: "communication" },
  { id: "5", text: "I design innovative lesson structures", category: "creativity" },
  { id: "6", text: "I effectively organize curriculum sequences", category: "planning" },
  { id: "7", text: "I facilitate productive team meetings", category: "leadership" },
  { id: "8", text: "I connect with students from diverse backgrounds", category: "communication" },
  { id: "9", text: "I integrate technology creatively in lessons", category: "creativity" },
  { id: "10", text: "I coordinate cross-departmental projects", category: "collaboration" },
  { id: "11", text: "I develop long-term professional goals", category: "planning" },
  { id: "12", text: "I inspire others to try new teaching methods", category: "leadership" },
  { id: "13", text: "I adapt communication styles to my audience", category: "communication" },
  { id: "14", text: "I build strong professional networks", category: "collaboration" },
  { id: "15", text: "I systematically track student progress", category: "planning" }
];

const strengthsProfiles = {
  'Creative Facilitator': {
    description: "Your strengths lie in visual communication and innovative teaching approaches",
    topStrengths: ['creativity', 'communication'],
    suggestions: [
      "Lead a Creative Teaching Workshop",
      "Try Visual Learning Templates",
      "Join Innovation in Education Community"
    ]
  },
  'Collaborative Leader': {
    description: "You excel at bringing people together and fostering teamwork",
    topStrengths: ['leadership', 'collaboration'],
    suggestions: [
      "Facilitate Cross-Departmental Projects",
      "Try Team-Teaching Approaches", 
      "Lead Professional Learning Communities"
    ]
  },
  'Strategic Communicator': {
    description: "You combine clear communication with systematic planning",
    topStrengths: ['communication', 'planning'],
    suggestions: [
      "Develop Curriculum Communication Plans",
      "Try Data-Driven Teaching Methods",
      "Join Educational Leadership Programs"
    ]
  },
  'Innovation Catalyst': {
    description: "You drive creative change through leadership and collaboration",
    topStrengths: ['creativity', 'leadership'],
    suggestions: [
      "Lead Educational Innovation Projects",
      "Try Design Thinking Workshops",
      "Join Creative Education Networks"
    ]
  },
  'Systems Organizer': {
    description: "You excel at planning and organizing collaborative efforts",
    topStrengths: ['planning', 'collaboration'],
    suggestions: [
      "Coordinate School-Wide Initiatives",
      "Try Project Management Tools",
      "Join Educational Administration Groups"
    ]
  }
};

interface StrengthsDiscoveryAssessmentProps {
  onComplete: (result: string, description: string) => void;
  currentResult?: {
    status: string;
    result?: string;
    description?: string;
  };
}

export function StrengthsDiscoveryAssessment({ onComplete, currentResult }: StrengthsDiscoveryAssessmentProps) {
  const [currentStatement, setCurrentStatement] = useState(0);
  const [responses, setResponses] = useState<Record<string, number>>({});
  const [showResults, setShowResults] = useState(false);
  const [result, setResult] = useState<keyof typeof strengthsProfiles | null>(null);

  const handleResponse = (statementId: string, value: number) => {
    setResponses(prev => ({ ...prev, [statementId]: value }));
  };

  const handleNext = () => {
    if (currentStatement < statements.length - 1) {
      setCurrentStatement(prev => prev + 1);
    } else {
      calculateResults();
    }
  };

  const handlePrevious = () => {
    if (currentStatement > 0) {
      setCurrentStatement(prev => prev - 1);
    }
  };

  const calculateResults = () => {
    const categoryScores = {
      creativity: 0,
      communication: 0,
      leadership: 0,
      planning: 0,
      collaboration: 0
    };

    const categoryCounts = {
      creativity: 0,
      communication: 0,
      leadership: 0,
      planning: 0,
      collaboration: 0
    };

    statements.forEach(statement => {
      const response = responses[statement.id];
      if (response) {
        categoryScores[statement.category] += response;
        categoryCounts[statement.category]++;
      }
    });

    // Calculate averages
    Object.keys(categoryScores).forEach(category => {
      if (categoryCounts[category as keyof typeof categoryCounts] > 0) {
        categoryScores[category as keyof typeof categoryScores] = 
          categoryScores[category as keyof typeof categoryScores] / categoryCounts[category as keyof typeof categoryCounts];
      }
    });

    // Find top two strengths
    const sortedStrengths = Object.entries(categoryScores)
      .sort(([,a], [,b]) => b - a)
      .slice(0, 2)
      .map(([category]) => category);

    // Determine profile based on top strengths
    const strengthKey = sortedStrengths.sort().join('-');
    const profileMap: Record<string, keyof typeof strengthsProfiles> = {
      'communication-creativity': 'Creative Facilitator',
      'collaboration-leadership': 'Collaborative Leader', 
      'communication-planning': 'Strategic Communicator',
      'creativity-leadership': 'Innovation Catalyst',
      'collaboration-planning': 'Systems Organizer'
    };

    const profile = profileMap[strengthKey] || 'Creative Facilitator';
    setResult(profile);
    setShowResults(true);
  };

  const handleComplete = () => {
    if (result) {
      const resultData = strengthsProfiles[result];
      onComplete(result, resultData.description);
    }
  };

  const progress = ((currentStatement + 1) / statements.length) * 100;
  const answeredStatements = Object.keys(responses).length;

  // Prepare radar chart data
  const getRadarData = () => {
    const categoryScores = {
      creativity: 0,
      communication: 0,
      leadership: 0,
      planning: 0,
      collaboration: 0
    };

    const categoryCounts = {
      creativity: 0,
      communication: 0,
      leadership: 0,
      planning: 0,
      collaboration: 0
    };

    statements.forEach(statement => {
      const response = responses[statement.id];
      if (response) {
        categoryScores[statement.category] += response;
        categoryCounts[statement.category]++;
      }
    });

    return Object.entries(categoryScores).map(([category, score]) => ({
      category: category.charAt(0).toUpperCase() + category.slice(1),
      score: categoryCounts[category as keyof typeof categoryCounts] > 0 
        ? Math.round((score / categoryCounts[category as keyof typeof categoryCounts]) * 20) // Convert to 0-100 scale
        : 0
    }));
  };

  if (showResults && result) {
    const resultData = strengthsProfiles[result];
    const radarData = getRadarData();
    
    return (
      <div className="space-y-6">
        <Card className="bg-gradient-to-r from-purple-50 to-pink-50 border-purple-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <CheckCircle className="w-5 h-5 text-green-600" />
              Your Strengths Profile: {result}
            </CardTitle>
            <CardDescription>{resultData.description}</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid md:grid-cols-2 gap-6">
              <div className="space-y-4">
                <h4 className="font-medium">Leadership & Development Opportunities</h4>
                <div className="space-y-2">
                  {resultData.suggestions.map((suggestion, index) => (
                    <Button 
                      key={index} 
                      variant="outline" 
                      size="sm" 
                      className="w-full justify-start text-sm h-auto py-2"
                    >
                      <ExternalLink className="w-3 h-3 mr-2" />
                      {suggestion}
                    </Button>
                  ))}
                </div>
              </div>
              
              <div>
                <h4 className="font-medium mb-3">Strengths Radar</h4>
                <div className="w-full h-[200px]">
                  <ChartContainer config={{}} className="w-full h-full">
                    <ResponsiveContainer width="100%" height="100%">
                      <RadarChart data={radarData}>
                        <PolarGrid />
                        <PolarAngleAxis dataKey="category" className="text-xs" />
                        <PolarRadiusAxis angle={90} domain={[0, 100]} tick={false} />
                        <Radar
                          name="Strength Level"
                          dataKey="score"
                          stroke="hsl(var(--primary))"
                          fill="hsl(var(--primary))"
                          fillOpacity={0.3}
                          strokeWidth={2}
                        />
                        <ChartTooltip content={<ChartTooltipContent />} />
                      </RadarChart>
                    </ResponsiveContainer>
                  </ChartContainer>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
        
        <div className="flex justify-center">
          <Button onClick={handleComplete} className="px-8">
            Save Results
          </Button>
        </div>
      </div>
    );
  }

  const scaleLabels = [
    "Strongly Disagree",
    "Disagree", 
    "Neutral",
    "Agree",
    "Strongly Agree"
  ];

  return (
    <div className="space-y-6">
      {/* Progress */}
      <div className="space-y-2">
        <div className="flex justify-between text-sm">
          <span>Statement {currentStatement + 1} of {statements.length}</span>
          <span>{answeredStatements} answered</span>
        </div>
        <Progress value={progress} className="h-2" />
      </div>

      {/* Statement */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">
            {statements[currentStatement].text}
          </CardTitle>
          <CardDescription>
            Rate how much you agree with this statement (1 = Strongly Disagree, 5 = Strongly Agree)
          </CardDescription>
        </CardHeader>
        <CardContent>
          <RadioGroup
            value={responses[statements[currentStatement].id]?.toString() || ""}
            onValueChange={(value) => handleResponse(statements[currentStatement].id, parseInt(value))}
          >
            {[1, 2, 3, 4, 5].map((value) => (
              <div key={value} className="flex items-center space-x-2 p-3 rounded-lg hover:bg-accent/50 transition-colors">
                <RadioGroupItem value={value.toString()} id={value.toString()} />
                <Label htmlFor={value.toString()} className="flex-1 cursor-pointer">
                  <span className="font-medium mr-2">{value}</span>
                  {scaleLabels[value - 1]}
                </Label>
              </div>
            ))}
          </RadioGroup>
        </CardContent>
      </Card>

      {/* Navigation */}
      <div className="flex justify-between">
        <Button 
          variant="outline" 
          onClick={handlePrevious}
          disabled={currentStatement === 0}
        >
          Previous
        </Button>
        
        <Button 
          onClick={handleNext}
          disabled={!responses[statements[currentStatement].id]}
        >
          {currentStatement === statements.length - 1 ? 'View Results' : 'Next'}
        </Button>
      </div>
    </div>
  );
}
